<template>
  <div class="box">
    <div class="btn">
      <el-button type="primary" plain @click="dialogVisible = true"><el-icon>
          <Plus />
        </el-icon>新增</el-button>
      <el-button type="success" :plain="true" @click="open1"><el-icon>
          <Edit />
        </el-icon>修改</el-button>
      <el-button type="danger" :plain="true" @click="open2"><el-icon>
          <Delete />
        </el-icon>删除</el-button>
    </div>
    <div>
      <span class="el-tag el-tag--default el-tag--light"><span class="el-tag__content">待处理任务列表</span><!--v-if--></span>
      <el-table :data="unapprovedTableData" style="width: 100%">
        <el-table-column type="selection" width="55" header-align="center" align="center" />
        <el-table-column property="name" label="客户名称" width="120" header-align="center" align="center" />
        <el-table-column property="phone" label="手机号码" width="120" header-align="center" align="center" />
        <el-table-column property="channelName" label="渠道名称" width="120" show-overflow-tooltip header-align="center"
          align="center" />
        <el-table-column property="activityName" label="活动名称" header-align="center" align="center" />
        <el-table-column property="courseName" label="课程名称" header-align="center" align="center" />
        <el-table-column property="contractPrice" label="合同金额" header-align="center" align="center" />
        <el-table-column label="操作" header-align="center" align="center" class="tak">
          <template #default="scope">
            <button class="el-button el-button--text el-button--default" type="button"><i class="el-icon"><svg
                  viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg   SVG namespace SVG namespace  ">
                  <path fill="currentColor"
                    d="M512 160c320 0 512 352 512 352S832 864 512 864 0 512 0 512s192-352 512-352zm0 64c-225.28 0-384.128 208.064-436.8 288 52.608 79.872 211.456 288 436.8 288 225.28 0 384.128-208.064 436.8-288-52.608-79.872-211.456-288-436.8-288zm0 64a224 224 0 1 1 0 448 224 224 0 0 1 0-448zm0 64a160.192 160.192 0 0 0-160 160c0 88.192 71.744 160 160 160s160-71.808 160-160-71.744-160-160-160z">
                  </path>
                </svg></i><span class="">查看 </span></button>
            <button class="el-button el-button--text el-button--default" type="button"><i class="el-icon"><svg
                  viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg   SVG namespace SVG namespace  ">
                  <path fill="currentColor"
                    d="M832 384H576V128H192v768h640V384zm-26.496-64L640 154.496V320h165.504zM160 64h480l256 256v608a32 32 0 0 1-32 32H160a32 32 0 0 1-32-32V96a32 32 0 0 1 32-32zm160 448h384v64H320v-64zm0-192h160v64H320v-64zm0 384h384v64H320v-64z">
                  </path>
                </svg></i><span class="">预览 </span></button>
          </template>
        </el-table-column>
      </el-table>
      <el-divider />
      <span class="el-tag el-tag--success el-tag--default el-tag--light"><span
          class="el-tag__content">已提交未审批任务列表</span><!--v-if--></span>
      <el-table :data="committedTableData" style="width: 100%">
        <el-table-column type="selection" width="55" header-align="center" align="center" />
        <el-table-column property="name" label="客户名称" width="120" header-align="center" align="center" />
        <el-table-column property="phone" label="手机号码" width="120" header-align="center" align="center" />
        <el-table-column property="channelName" label="渠道名称" width="120" show-overflow-tooltip header-align="center"
          align="center" />
        <el-table-column property="activityName" label="活动名称" header-align="center" align="center" />
        <el-table-column property="courseName" label="课程名称" header-align="center" align="center" />
        <el-table-column property="contractPrice" label="合同金额" header-align="center" align="center" />
      </el-table>
      <el-divider />
      <span class="el-tag el-tag--danger el-tag--default el-tag--light"><span
          class="el-tag__content">审批完成任务列表</span><!--v-if--></span>
      <el-table :data="approvedTableData" style="width: 100%">
        <el-table-column type="selection" width="55" header-align="center" align="center" />
        <el-table-column property="name" label="客户名称" width="120" header-align="center" align="center" />
        <el-table-column property="phone" label="手机号码" width="120" header-align="center" align="center" />
        <el-table-column property="channelName" label="渠道名称" width="120" show-overflow-tooltip header-align="center"
          align="center" />
        <el-table-column property="activityName" label="活动名称" header-align="center" align="center" />
        <el-table-column property="courseName" label="课程名称" header-align="center" align="center" />
        <el-table-column property="contractPrice" label="合同金额" header-align="center" align="center" />
        <el-table-column property="reason" label="备注信息" header-align="center" align="center" />
        <el-table-column label="操作" header-align="center" align="center" class="tak">
          <template #default="scope">
            <button @click="openDialog(scope.row)" class="el-button el-button--text el-button--default" type="button"><i
                class="el-icon"><svg viewBox="0 0 1024 1024"
                  xmlns="http://www.w3.org/2000/svg   SVG namespace SVG namespace  ">
                  <path fill="currentColor"
                    d="M512 160c320 0 512 352 512 352S832 864 512 864 0 512 0 512s192-352 512-352zm0 64c-225.28 0-384.128 208.064-436.8 288 52.608 79.872 211.456 288 436.8 288 225.28 0 384.128-208.064 436.8-288-52.608-79.872-211.456-288-436.8-288zm0 64a224 224 0 1 1 0 448 224 224 0 0 1 0-448zm0 64a160.192 160.192 0 0 0-160 160c0 88.192 71.744 160 160 160s160-71.808 160-160-71.744-160-160-160z">
                  </path>
                </svg></i><span class="">查看 </span></button>
            <button class="el-button el-button--text el-button--default" type="button"><i class="el-icon"><svg
                  viewBox="0 0 1024 1024" xmlns="http://www.w3.org/el-svg   SVG namespace SVG namespace  ">
                  <path fill="currentColor"
                    d="M832 384H576V128H192v768h640V384zm-26.496-64L640 154.496V320h165.504zM160 64h480l256 256v608a32 32 0 0 1-32 32H160a32 32 0 0 1-32-32V96a32 32 0 0 1 32-32zm160 448h384v64H320v-64zm0-192h160v64H320v-64zm0 384h384v64H320v-64z">
                  </path>
                </svg></i><span class="">预览 </span></button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 详情 -->
    <div>
      <el-dialog v-model="centerDialogVisible" title="合同详情" width="500" center>
        <div>
          <div class="col1">
            <p class="italic-text"><strong>合同编号<br></strong> <span class="ins">{{ selectedRow?.contractId }}</span></p>
            <p class="italic-text"><strong>客户手机号码<br></strong> <span class="ins">{{ selectedRow?.phone }}</span></p>
            <p class="italic-text"><strong>客户姓名<br></strong> <span class="ins">{{ selectedRow?.name }}</span></p>
          </div>
          <div class="col1">
            <p class="italic-text"><strong>课程分类<br></strong> <span class="ins">游泳课</span></p>
            <p class="italic-text"><strong>课程名称<br></strong> <span class="ins">{{ selectedRow?.courseName }}</span></p>
            <p class="italic-text"><strong>渠道名称<br></strong> <span class="ins">{{ selectedRow?.channelName }}</span></p>
          </div>
          <div class="col1">
            <p class="italic-text"><strong>活动名称<br></strong> <span class="ins">{{ selectedRow?.activityName }}</span></p>
            <p class="italic-text"><strong>合同状态<br></strong> <span class="ins">审批通过</span></p>
            <p class="italic-text"><strong>合同金额<br></strong> <span class="ins">{{ selectedRow?.contractPrice }}</span></p>
          </div>
          <div class="col1">
            <p class="italic-text"><strong>课程价格<br></strong> <span class="ins">100</span></p>
            <p class="italic-text"><strong>折扣类型<br></strong> <span class="ins">代金券</span></p>
            <p class="italic-text"><strong>合同审批人<br></strong> <span class="ins">admin</span></p>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="centerDialogVisible = false">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 新增部分 -->
    <div>
      <el-dialog v-model="dialogVisible" title="添加合同" width="600px" center>
        <el-form :model="contractForm" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号" required>
                <el-input v-model="contractForm.phone" placeholder="请输入手机号" @input="fetchUserInfo"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户姓名" required>
                <el-input v-model="contractForm.name" placeholder="请输入客户姓名" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="渠道来源">
                <el-select v-model="contractForm.channel" placeholder="渠道来源" disabled>
                  <el-option label="小程序推广" value="6"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="活动信息">
                <el-select v-model="contractForm.activity" placeholder="活动信息" disabled>
                  <el-option label="1212" value="24"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="课程分类">
                <el-select v-model="contractForm.courseCategory" placeholder="课程分类" disabled>
                  <el-option label="课程分类" value="category"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="购买课程">
                <el-select v-model="contractForm.course" placeholder="请选择" disabled>
                  <el-option label="购买课程" value="course"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="审批部门">
                <el-cascader
                  v-model="contractForm.approvalDepartment"
                  :options="departmentOptions"
                  placeholder="请选择归属部门"
                  :props="{ checkStrictly: true }">
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审批人">
                <el-select v-model="contractForm.approver" placeholder="选择用户">
                  <el-option label="审批人" value="approver"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同价格" required>
                <el-input-number :step="100" v-model="contractForm.price" :min="0" @change="handleChange"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同原件">
                <el-upload
                  action="#"
                  list-type="text"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                  :limit="1"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :before-upload="beforeUpload">
                  <el-button slot="trigger" size="small" type="primary">选择合同原件</el-button>
                  <br>
                  <div slot="tip" class="el-upload__tip">合同原件大小不能超过 5MB。</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitContract">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { listUnapproved, listCommitted, listApproved } from '@/api/tienchin/hetong'; // 确保引入路径正确

interface User {
  date: string;
  name: string;
  phone: string;
  address: string;
  channelName: string;
  activityName: string;
  courseName: string;
  contractPrice: string;
  reason: string;
}
const contractForm = ref({
  phone: '',
  name: '',
  channel: '',
  activity: '',
  courseCategory: '',
  course: '',
  approvalDepartment: [],
  approver: '',
  price: ''
});
const departmentOptions = ref([
  {
    value: 'company',
    label: 'TienChin健身科技',
    children: [
     {
       value: 'shenzhen',
       label: '深圳总公司',
        children: [
        { value: 'test', label: '测试部门' },
        { value: 'operation', label: '运维部门' }
       ]
      }
    ]
  }
]);
const fileList = ref([]);
const unapprovedTableData = ref<User[]>([]);
const committedTableData = ref<User[]>([]);
const approvedTableData = ref<User[]>([]);

const selectedRow = ref<User | null>(null);
const centerDialogVisible = ref(false);
const dialogVisible = ref(false);

const selectedIds = ref<number[]>([]);

const openDialog = (row: User) => {
  selectedRow.value = row;
  centerDialogVisible.value = true;
  console.log(selectedRow.value, "看一下value");
};

const handleSelectionChange = (selection: User[]) => {
  selectedIds.value = selection.map(item => item.id);
};

const handleExceed = () => {
  console.log('文件超出限制');
};

const handleRemove = (file: any, fileList: any) => {
  console.log(file, fileList);
};

const handleSuccess = (response: any, file: any, fileList: any) => {
  console.log(response, file, fileList);
};

const open1 = () => {
  if (selectedIds.value.length > 0) {
    // 执行修改操作
    console.log('修改', selectedIds.value);
  } else {
    ElMessage.error('请先选择要修改的行');
  }
};

const open2 = () => {
  if (selectedIds.value.length > 0) {
    // 执行删除操作
    console.log('删除', selectedIds.value);
  } else {
    ElMessage.error('请先选择要删除的行');
  }
};

const beforeUpload = (file: any) => {
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    alert('文件大小不能超过 5MB!');
  }
  return isLt5M;
};

const submitContract = () => {
  console.log('提交合同', contractForm.value);
  ElMessage.error('添加失败 请重试.');
  contractForm.value = {
    phone: '',
    name: '',
    channel: '',
    activity: '',
    courseCategory: '',
    course: '',
    approvalDepartment: [],
    approver: '',
    price: ''
  };
  // dialogVisible.value = false;
};

const fetchUserInfo = async () => {
  const phone = contractForm.value.phone;
  try {
    const response = await fetch(`/api/userinfo?phone=${phone}`);
    const data = await response.json();
   if (data.success) {
     contractForm.value.name = data.data.name;
     contractForm.value.channel = data.data.channelId;
     contractForm.value.activity = data.data.activityId;
     contractForm.value.course = data.data.courseId;
   } else {
     contractForm.value.name = '';
     contractForm.value.channel = '';
     contractForm.value.activity = '';
     contractForm.value.course = '';
    ElMessage.error('未找到对应用户信息');
  }
 } catch (error) {
   console.error('Failed to fetch user info:', error);
   ElMessage.error('获取用户信息失败');
 }
};

onMounted(async () => {
  try {
    // 调用接口获取待处理任务列表
    const unapprovedResponse = await listUnapproved({});
    unapprovedTableData.value = unapprovedResponse.rows;
    console.log(unapprovedTableData.value);

    // 调用接口获取已提交未审批任务列表
    const committedResponse = await listCommitted({});
    committedTableData.value = committedResponse.rows;
    console.log(committedTableData.value);

    // 调用接口获取审批完成任务列表
    const approvedResponse = await listApproved({});
    approvedTableData.value = approvedResponse.rows;
    console.log(approvedTableData.value);
  } catch (error) {
    console.error('Failed to fetch data:', error);
  }
});
</script>

<style scoped lang="scss">
.box {
  padding: 20px;
}

.btn {
  margin-bottom: 20px;
}
.col1{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  width: 450px;
}
.italic-text .ins{
  font-style: normal;
  color: #999;
}
p{
  width: 100px;
  height: 50px;
}
::v-deep .el-upload{
  flex-direction: column !important;
}
::v-deep .el-upload__tip{
  margin-top: -34px !important;
}
.italic-text {
  font-style: italic;
}
</style>